package com.allwees.core.dao.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.allwees.core.common.constant.EDelete;
import com.allwees.core.common.constant.EStatus;
import com.allwees.core.common.util.UuidUtil;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * 指定字段自动填充处理器，对应{@code @TableField(fill = FieldFill.xxx)的字段}
 *
 * @author yangylsky
 *
 */
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {
	@Override
	public void insertFill(MetaObject metaObject) {
		setFieldValueByName("isDeleted", EDelete.UNDELETED.value(), metaObject);
		Date now = new Date();
		setFieldValueByName("createdAt", now, metaObject);
		setFieldValueByName("updatedAt", now, metaObject);
		setFieldValueByName("status", EStatus.NORMAL.value(), metaObject);
		setFieldValueByName("uuid", UuidUtil.generate(), metaObject);
		setFieldValueByName("idx", 0, metaObject);
	}

	@Override
	public void updateFill(MetaObject metaObject) {
		setFieldValueByName("updatedAt", new Date(), metaObject);
	}

	private void setFieldValueByName(String field, Object value, MetaObject metaObject) {
		if(null == metaObject.findProperty(field, false) || null != metaObject.getValue(field)) {
			return;
		}
		metaObject.setValue(field, value);
	}
}
